import * as express from "express";
import apiSv from "../../services/apiSV";
import * as multer from "multer";
import * as crypto from "crypto";
import * as fs from "fs";
import * as axios from "axios";
import * as path from "path";

let router = express.Router();
const uploadDir = "uploads/";
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}
// 设置文件存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/"); // 文件存储路径
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname); // 文件名
  },
});
const upload = multer({ storage: storage });

router.post("/sendMessage", async (req, res, next) => {
  const { message, FileId, session_id } = req.body;
  const apiKey = "sk-028513aaf9894c49ae20afe23096a0a0";
  const appId = "33a556d4b4ac47089a75a8c7f0d5bbd1";
  const Url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
  const data = {
    input: {
      prompt: message,
      session_id: session_id,
    },
    parameters: {
      rag_options: {
        session_file_ids: FileId, // 替换为指定的临时文件 ID，多个请用逗号隔开
      },
    },

    debug: {},
  };
  try {
    const response = await axios.default.post(Url, data, {
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
    });
    return res.json({
      status: true,
      data: response.data,
    });
  } catch (e) {
    return next(e);
  }
});
router.post(
  "/upload-endpoint",
  upload.single("file"),
  async (req, res, next) => {
    try {
      if (!req.file) {
        return res
          .status(400)
          .json({ status: false, message: "No file uploaded" });
      }
      // 获取文件信息
      const filePath = req.file.path;
      const fileName = req.file.filename;
      const fileSize = req.file.size;
      // 计算文件的MD5值
      const fileBuffer = fs.readFileSync(filePath);
      const md5Hash = crypto.createHash("md5").update(fileBuffer).digest("hex");
      let data = await apiSv(req.api.v4.get, {
        action: "aitools.bailian.applyUploadLease",
        filename: fileName,
        md5: md5Hash,
        sizeInBytes: fileSize,
      });

      // 设置请求头
      const uploadData = data.data.lease;
      const headers = uploadData.Param.Headers;
      const FileUploadLeaseId = uploadData.FileUploadLeaseId;
      const response = await axios.default.put(
        uploadData.Param.Url,
        fileBuffer,
        {
          headers,
        }
      );
      console.log(response);
      let data2 = await apiSv(req.api.v4.get, {
        action: "aitools.bailian.addFile",
        leaseID: FileUploadLeaseId,
      });
      return res.json({
        status: true,
        data: data2,
        fileSize: fileSize,
      });
    } catch (e) {
      return next(e);
    }
  }
);
export default router;
